//
//  ZSNRHMPKViewController.swift
//  ZSNRongHeMPK
//
//  Created by zhaosuning on 2022/2/11.
//

import UIKit
import AgoraRtcKit

class ZSNRHMPKViewController: UIViewController, AgoraRtcEngineDelegate, AgoraRtcMediaPlayerDelegate, AVAudioPlayerDelegate {

    var viewBg: UIView!
    var agoraKit: AgoraRtcEngineKit!
    var mediaPlayerKit: AgoraRtcMediaPlayer!
    var lblshuoming3: UILabel!
    var audioPlayer: AVAudioPlayer!
    
    var scroView: UIScrollView!
    
    var localView: UIView!
    var remoteView: UIView!
    
    var mpkLocalView: UIView!
    var mpkremoteView: UIView!
    
    var intRole: Int = 0
    
    var txtview: UITextView!
    
    var useVoiceChat: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "MPK页"
        self.view.backgroundColor = UIColor.white
        
        scroView = UIScrollView.init()
        scroView.backgroundColor = UIColor.white
        scroView.showsVerticalScrollIndicator = false
        scroView.clipsToBounds = true
        scroView.bounces = true
        scroView.alwaysBounceVertical = true
        scroView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
        
        self.view.addSubview(scroView)
        
        
        if #available(iOS 13.0, *) {
            scroView.automaticallyAdjustsScrollIndicatorInsets = false
        } else {
            scroView.contentInsetAdjustmentBehavior=UIScrollView.ContentInsetAdjustmentBehavior.never
        }
        
        viewBg = UIView.init()
        viewBg.frame = CGRect(x: 0, y: 90, width: UIScreen.main.bounds.size.width, height: 1300)
        viewBg.backgroundColor = UIColor.white
        scroView.addSubview(viewBg)
        scroView.contentSize = CGSize(width: UIScreen.main.bounds.size.width, height: viewBg.frame.height)
        
//        let btnCreatePlayNoChannel = UIButton.init(frame: CGRect(x: 30, y: 90, width: 230, height: 45))
//        btnCreatePlayNoChannel.backgroundColor = UIColor.green
//        btnCreatePlayNoChannel.setTitle("创建MedPlayer no channel", for: .normal)
//        btnCreatePlayNoChannel.layer.cornerRadius = 20
//        btnCreatePlayNoChannel.titleLabel?.textAlignment = .center
//        btnCreatePlayNoChannel.layer.masksToBounds = true
//        btnCreatePlayNoChannel.titleLabel?.font = UIFont.systemFont(ofSize: 15)
//        btnCreatePlayNoChannel.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
//        btnCreatePlayNoChannel.addTarget(self, action: #selector(btnCreatePlayNoChannelAction), for: UIControl.Event.touchUpInside)
//        viewBg.addSubview(btnCreatePlayNoChannel)
        
        
        let btnInitRTC = UIButton.init(frame: CGRect(x: 5, y: 5, width: 155, height: 45))
        btnInitRTC.backgroundColor = UIColor.green
        btnInitRTC.setTitle("初始化RTC", for: .normal)
        btnInitRTC.layer.cornerRadius = 22
        btnInitRTC.titleLabel?.textAlignment = .center
        btnInitRTC.layer.masksToBounds = true
        btnInitRTC.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btnInitRTC.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnInitRTC.addTarget(self, action: #selector(btnInitRTCAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnInitRTC)
        
        let btnGameStreamBeforeJoin = UIButton.init(frame: CGRect(x: 5, y: 60, width: 200, height: 45))
        btnGameStreamBeforeJoin.backgroundColor = UIColor.green
        btnGameStreamBeforeJoin.setTitle("频道前RTC为GameStream", for: .normal)
        btnGameStreamBeforeJoin.layer.cornerRadius = 22
        btnGameStreamBeforeJoin.titleLabel?.textAlignment = .center
        btnGameStreamBeforeJoin.layer.masksToBounds = true
        btnGameStreamBeforeJoin.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btnGameStreamBeforeJoin.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnGameStreamBeforeJoin.addTarget(self, action: #selector(btnGameStreamBeforeJoinAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnGameStreamBeforeJoin)
        
        let btnRoleBroadcast = UIButton.init(frame: CGRect(x: 215, y: 60, width: 130, height: 45))
        btnRoleBroadcast.backgroundColor = UIColor.green
        btnRoleBroadcast.setTitle("设为主播", for: .normal)
        btnRoleBroadcast.layer.cornerRadius = 22
        btnRoleBroadcast.titleLabel?.textAlignment = .center
        btnRoleBroadcast.layer.masksToBounds = true
        btnRoleBroadcast.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btnRoleBroadcast.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnRoleBroadcast.addTarget(self, action: #selector(btnRoleBroadcastAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnRoleBroadcast)
        
        let btnChatRoomBeforeJoin = UIButton.init(frame: CGRect(x: 5, y: 115, width: 200, height: 45))
        btnChatRoomBeforeJoin.backgroundColor = UIColor.green
        btnChatRoomBeforeJoin.setTitle("频道前RTC为ChatRoom", for: .normal)
        btnChatRoomBeforeJoin.layer.cornerRadius = 22
        btnChatRoomBeforeJoin.titleLabel?.textAlignment = .center
        btnChatRoomBeforeJoin.layer.masksToBounds = true
        btnChatRoomBeforeJoin.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btnChatRoomBeforeJoin.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnChatRoomBeforeJoin.addTarget(self, action: #selector(btnChatRoomBeforeJoinAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnChatRoomBeforeJoin)
        
        let btnRoleAudience = UIButton.init(frame: CGRect(x: 215, y: 115, width: 130, height: 45))
        btnRoleAudience.backgroundColor = UIColor.green
        btnRoleAudience.setTitle("设为观众", for: .normal)
        btnRoleAudience.layer.cornerRadius = 22
        btnRoleAudience.titleLabel?.textAlignment = .center
        btnRoleAudience.layer.masksToBounds = true
        btnRoleAudience.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btnRoleAudience.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnRoleAudience.addTarget(self, action: #selector(btnRoleAudienceAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnRoleAudience)
        
        let btnCreateInitMediaPlay = UIButton.init(frame: CGRect(x: 5, y: 170, width: 155, height: 45))
        btnCreateInitMediaPlay.backgroundColor = UIColor.green
        btnCreateInitMediaPlay.setTitle("创建AgoraMedPlayer", for: .normal)
        btnCreateInitMediaPlay.layer.cornerRadius = 22
        btnCreateInitMediaPlay.titleLabel?.textAlignment = .center
        btnCreateInitMediaPlay.layer.masksToBounds = true
        btnCreateInitMediaPlay.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btnCreateInitMediaPlay.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnCreateInitMediaPlay.addTarget(self, action: #selector(btnCreateInitMediaPlayAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnCreateInitMediaPlay)
        
        let btnOpenClick = UIButton.init(frame: CGRect(x: 170, y:170, width: 120, height: 45))
        btnOpenClick.backgroundColor = UIColor.green
        btnOpenClick.setTitle("Open MPK URL", for: .normal)
        btnOpenClick.layer.cornerRadius = 22
        btnOpenClick.titleLabel?.textAlignment = .center
        btnOpenClick.layer.masksToBounds = true
        btnOpenClick.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btnOpenClick.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnOpenClick.addTarget(self, action: #selector(btnOpenClickAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnOpenClick)
        
        let btnPlayClick = UIButton.init(frame: CGRect(x: 5, y:225, width: 110, height: 45))
        btnPlayClick.backgroundColor = UIColor.green
        btnPlayClick.setTitle("Play播放MPK", for: .normal)
        btnPlayClick.layer.cornerRadius = 22
        btnPlayClick.titleLabel?.textAlignment = .center
        btnPlayClick.layer.masksToBounds = true
        btnPlayClick.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btnPlayClick.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnPlayClick.addTarget(self, action: #selector(btnPlayClickAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnPlayClick)
        
        
        let btnStopClick = UIButton.init(frame: CGRect(x: 125, y:225, width: 110, height: 45))
        btnStopClick.backgroundColor = UIColor.green
        btnStopClick.setTitle("Stop播放MPK", for: .normal)
        btnStopClick.layer.cornerRadius = 22
        btnStopClick.titleLabel?.textAlignment = .center
        btnStopClick.layer.masksToBounds = true
        btnStopClick.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btnStopClick.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnStopClick.addTarget(self, action: #selector(btnStopClickAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnStopClick)
        
        let btnDestroyPlay = UIButton.init(frame: CGRect(x: 245, y: 225, width: 100, height: 45))
        btnDestroyPlay.backgroundColor = UIColor.green
        btnDestroyPlay.setTitle("销毁MPK", for: .normal)
        btnDestroyPlay.layer.cornerRadius = 22
        btnDestroyPlay.titleLabel?.textAlignment = .center
        btnDestroyPlay.layer.masksToBounds = true
        btnDestroyPlay.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btnDestroyPlay.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnDestroyPlay.addTarget(self, action: #selector(btnDestroyPlayAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnDestroyPlay)
        
        let btnPalyAVPlayer = UIButton.init(frame: CGRect(x: 5, y: 280, width: 210, height: 40))
        btnPalyAVPlayer.backgroundColor = UIColor.green
        btnPalyAVPlayer.setTitle("进频道前播放AVAudioPlayer", for: .normal)
        btnPalyAVPlayer.layer.cornerRadius = 18
        btnPalyAVPlayer.titleLabel?.textAlignment = .center
        btnPalyAVPlayer.layer.masksToBounds = true
        btnPalyAVPlayer.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btnPalyAVPlayer.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnPalyAVPlayer.addTarget(self, action: #selector(btnPalyAVPlayerAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnPalyAVPlayer)
        
        let btnJoinChannel = UIButton.init(frame: CGRect(x: 5, y: 330, width: 140, height: 40))
        btnJoinChannel.backgroundColor = UIColor.green
        btnJoinChannel.setTitle("点击Join频道", for: .normal)
        //btnGot.setBackgroundImage(UIImage.init(named: "ic_take_photo_btn_bg"), for: UIControl.State.normal)
        btnJoinChannel.layer.cornerRadius = 20
        btnJoinChannel.titleLabel?.textAlignment = .center
        btnJoinChannel.layer.masksToBounds = true
        //btnGot.titleLabel?.font = UIFont.init(name: "Montserrat-Medium", size: 18 * SCREENWB)
        btnJoinChannel.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btnJoinChannel.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnJoinChannel.addTarget(self, action: #selector(btnJoinChannelClick), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnJoinChannel)
        
        let btnLeaveClick = UIButton.init(frame: CGRect(x: 155, y: 330, width: 100, height: 40))
        btnLeaveClick.backgroundColor = UIColor.green
        btnLeaveClick.setTitle("离开频道", for: .normal)
        btnLeaveClick.layer.cornerRadius = 20
        btnLeaveClick.titleLabel?.textAlignment = .center
        btnLeaveClick.layer.masksToBounds = true
        btnLeaveClick.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btnLeaveClick.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnLeaveClick.addTarget(self, action: #selector(btnLeaveChannelAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnLeaveClick)
        
        let btnDestroyRTC = UIButton.init(frame: CGRect(x: 265, y: 330, width: 100, height: 40))
        btnDestroyRTC.backgroundColor = UIColor.green
        btnDestroyRTC.setTitle("销毁RTC", for: .normal)
        btnDestroyRTC.layer.cornerRadius = 20
        btnDestroyRTC.titleLabel?.textAlignment = .center
        btnDestroyRTC.layer.masksToBounds = true
        btnDestroyRTC.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btnDestroyRTC.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnDestroyRTC.addTarget(self, action: #selector(btnDestroyRTCAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnDestroyRTC)
        
        let btna2dp0 = UIButton.init(frame: CGRect(x: 5, y: 380, width: 70, height: 40))
        btna2dp0.backgroundColor = UIColor.green
        btna2dp0.setTitle("a2dp 0", for: .normal)
        btna2dp0.layer.cornerRadius = 20
        btna2dp0.titleLabel?.textAlignment = .center
        btna2dp0.layer.masksToBounds = true
        //btnGot.titleLabel?.font = UIFont.init(name: "Montserrat-Medium", size: 18 * SCREENWB)
        btna2dp0.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btna2dp0.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btna2dp0.addTarget(self, action: #selector(btna2dp0Click), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btna2dp0)
        
        let btna2dp1 = UIButton.init(frame: CGRect(x: 85, y: 380, width: 70, height: 40))
        btna2dp1.backgroundColor = UIColor.green
        btna2dp1.setTitle("a2dp 1", for: .normal)
        btna2dp1.layer.cornerRadius = 20
        btna2dp1.titleLabel?.textAlignment = .center
        btna2dp1.layer.masksToBounds = true
        btna2dp1.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btna2dp1.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btna2dp1.addTarget(self, action: #selector(btna2dp1Click), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btna2dp1)
        
        let btnSetClick = UIButton.init(frame: CGRect(x: 170, y:380, width: 205, height: 40))
        btnSetClick.backgroundColor = UIColor.green
        btnSetClick.setTitle("设置AVAudioSession为soloAmbient", for: .normal)
        btnSetClick.layer.cornerRadius = 20
        btnSetClick.titleLabel?.textAlignment = .center
        btnSetClick.layer.masksToBounds = true
        btnSetClick.titleLabel?.font = UIFont.systemFont(ofSize: 11)
        btnSetClick.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnSetClick.addTarget(self, action: #selector(btnSetClickAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnSetClick)
        
        let btnScenarioGameStreaming = UIButton.init(frame: CGRect(x: 10, y: 440, width: 150, height: 40))
        btnScenarioGameStreaming.backgroundColor = UIColor.green
        btnScenarioGameStreaming.setTitle("频道内切换为GameStream", for: .normal)
        btnScenarioGameStreaming.layer.cornerRadius = 20
        btnScenarioGameStreaming.titleLabel?.textAlignment = .center
        btnScenarioGameStreaming.layer.masksToBounds = true
        btnScenarioGameStreaming.titleLabel?.font = UIFont.systemFont(ofSize: 11)
        btnScenarioGameStreaming.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnScenarioGameStreaming.addTarget(self, action: #selector(btnScenarioGameStreamingAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnScenarioGameStreaming)
        
        let btnScenarioChatRoom = UIButton.init(frame: CGRect(x: 170, y: 440, width: 150, height: 40))
        btnScenarioChatRoom.backgroundColor = UIColor.green
        btnScenarioChatRoom.setTitle("频道内切换为ChatRoom", for: .normal)
        btnScenarioChatRoom.layer.cornerRadius = 20
        btnScenarioChatRoom.titleLabel?.textAlignment = .center
        btnScenarioChatRoom.layer.masksToBounds = true
        btnScenarioChatRoom.titleLabel?.font = UIFont.systemFont(ofSize: 11)
        btnScenarioChatRoom.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnScenarioChatRoom.addTarget(self, action: #selector(btnScenarioChatRoomAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnScenarioChatRoom)
        
//        let lblshuoming = UILabel.init()
//        lblshuoming.frame = CGRect(x: 3, y: 550, width: 360, height: 18)
//        lblshuoming.text = "无频道时：创建MPK无频道-Open-Play-Stop-销毁"
//        lblshuoming.font = UIFont.systemFont(ofSize: 11)
//        lblshuoming.textColor = UIColor.blue
//        lblshuoming.backgroundColor = UIColor.white
//        viewBg.addSubview(lblshuoming)
//
//        let lblshuoming2 = UILabel.init()
//        lblshuoming2.frame = CGRect(x: 3, y: 569, width: 360, height: 18)
//        lblshuoming2.text = "有频道时：加入频道-创建MPK有频道-Open-Play-Stop-销毁"
//        lblshuoming2.font = UIFont.systemFont(ofSize: 11)
//        lblshuoming2.textColor = UIColor.blue
//        lblshuoming2.backgroundColor = UIColor.white
//        viewBg.addSubview(lblshuoming2)
        
//        let lblshuoming3 = UILabel.init()
//        lblshuoming3.frame = CGRect(x: 3, y: 588, width: 360, height: 18)
//        lblshuoming3.text = "MPK在有频道和无频道切换时，可以先stop-再销毁MPK-重新创建MPK"
//        lblshuoming3.font = UIFont.systemFont(ofSize: 11)
//        lblshuoming3.textColor = UIColor.red
//        lblshuoming3.backgroundColor = UIColor.white
//        self.view.addSubview(lblshuoming3)
        
        //let lblshuoming3 = UILabel.init()
        lblshuoming3 = UILabel.init()
        lblshuoming3.frame = CGRect(x: 3, y: 592, width: 360, height: 24)
        lblshuoming3.text = ""
        lblshuoming3.font = UIFont.systemFont(ofSize: 20)
        lblshuoming3.textColor = UIColor.red
        lblshuoming3.backgroundColor = UIColor.white
        viewBg.addSubview(lblshuoming3)
        
        localView = UIView.init()
        localView.backgroundColor = UIColor.yellow
        localView.frame = CGRect(x: 5, y: 490, width: 170, height: 170)
        viewBg.addSubview(localView)
        
        mpkLocalView = UIView.init()
        mpkLocalView.backgroundColor = UIColor.yellow
        mpkLocalView.frame = CGRect(x: 180, y: 490, width: 170, height: 170)
        viewBg.addSubview(mpkLocalView)
        
        remoteView = UIView.init()
        remoteView.frame = CGRect(x: 5, y: 670, width: 170, height: 170)
        remoteView.backgroundColor = UIColor.blue
        viewBg.addSubview(remoteView)
        
        mpkremoteView = UIView.init()
        mpkremoteView.frame = CGRect(x: 180, y: 670, width: 170, height: 170)
        mpkremoteView.backgroundColor = UIColor.blue
        viewBg.addSubview(mpkremoteView)
        
        let btnpublishPlayerVideo = UIButton.init(frame: CGRect(x: 5, y: 850, width: 180, height: 40))
        btnpublishPlayerVideo.backgroundColor = UIColor.green
        btnpublishPlayerVideo.setTitle("publishPlayerVideo", for: .normal)
        btnpublishPlayerVideo.layer.cornerRadius = 20
        btnpublishPlayerVideo.titleLabel?.textAlignment = .center
        btnpublishPlayerVideo.layer.masksToBounds = true
        //btnGot.titleLabel?.font = UIFont.init(name: "Montserrat-Medium", size: 18 * SCREENWB)
        btnpublishPlayerVideo.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btnpublishPlayerVideo.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnpublishPlayerVideo.addTarget(self, action: #selector(btnpublishPlayerVideoClick), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnpublishPlayerVideo)
        
        let btnpublishPlayerAudio = UIButton.init(frame: CGRect(x: 195, y: 850, width: 180, height: 40))
        btnpublishPlayerAudio.backgroundColor = UIColor.green
        btnpublishPlayerAudio.setTitle("publishPlayerAudio", for: .normal)
        btnpublishPlayerAudio.layer.cornerRadius = 20
        btnpublishPlayerAudio.titleLabel?.textAlignment = .center
        btnpublishPlayerAudio.layer.masksToBounds = true
        //btnGot.titleLabel?.font = UIFont.init(name: "Montserrat-Medium", size: 18 * SCREENWB)
        btnpublishPlayerAudio.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btnpublishPlayerAudio.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnpublishPlayerAudio.addTarget(self, action: #selector(btnpublishPlayerAudioClick), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnpublishPlayerAudio)
        
        txtview = UITextView.init()
        txtview.frame = CGRect(x: 5, y: 900, width: 315, height: 100)
        txtview.backgroundColor = UIColor.lightGray
        txtview.textColor = UIColor.blue
        viewBg.addSubview(txtview)
        
        let btnGetClick = UIButton.init(frame: CGRect(x: 5, y: 1010, width: 158, height: 40))
        btnGetClick.backgroundColor = UIColor.green
        btnGetClick.setTitle("查看AVAudioSession", for: .normal)
        btnGetClick.layer.cornerRadius = 20
        btnGetClick.titleLabel?.textAlignment = .center
        btnGetClick.layer.masksToBounds = true
        btnGetClick.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btnGetClick.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnGetClick.addTarget(self, action: #selector(btnGetClickAction), for: UIControl.Event.touchUpInside)
        viewBg.addSubview(btnGetClick)
        
        
        
        if let bundlePath = Bundle.main.path(forResource: "jiandanai", ofType: "mp3") {
            let url = URL.init(fileURLWithPath: bundlePath)
            do {
                try audioPlayer = AVAudioPlayer(contentsOf: url)
                audioPlayer.delegate = self
                audioPlayer.prepareToPlay()
                NSLog("打印了 AVAudioPlayer 准备")
            } catch let error as NSError {
                NSLog("打印了 audioPlayer error \(error.localizedDescription)")
            }

        }

    }
    
    func setupLocalVideo() {
        // 启用视频模块
        //agoraKit?.enableVideo()
        let videoCanvas = AgoraRtcVideoCanvas()
        videoCanvas.uid = 0
        videoCanvas.renderMode = .hidden
        videoCanvas.view = localView
        // 设置本地视图
        agoraKit?.setupLocalVideo(videoCanvas)
        agoraKit.startPreview()
    }
    
    func setupRemoteVideo(_ uid: UInt) {
        let videoCanvas = AgoraRtcVideoCanvas()
        videoCanvas.uid = uid
        videoCanvas.renderMode = .hidden
        videoCanvas.view = remoteView
        // 设置远端视图
        agoraKit?.setupRemoteVideo(videoCanvas)
    }
    
    func setupMPKRemoteVideo(_ uid: UInt) {
        let videoCanvas = AgoraRtcVideoCanvas()
        videoCanvas.uid = uid
        videoCanvas.renderMode = .hidden
        videoCanvas.view = mpkremoteView
        // 设置远端视图
        agoraKit?.setupRemoteVideo(videoCanvas)
    }
    
    @objc func btnpublishPlayerVideoClick() {
        NSLog("打印了 btnpublishPlayerVideoClick")
        //if agoraKit != nil && mediaPlayerKit != nil {
            //agoraKit.publishPlayerVideo
            //agoraKit.pushExternalVideoFrame(<#T##frame: AgoraVideoFrame##AgoraVideoFrame#>)
            //agoraKit.publisher(for: <#T##KeyPath<AgoraRtcEngineKit, Value>#>, options: <#T##NSKeyValueObservingOptions#>)
            
            mediaPlayerKit.publishPlayerVideo()
        //}
    }
    
    @objc func btnpublishPlayerAudioClick() {
        //if agoraKit != nil && mediaPlayerKit != nil {
            NSLog("打印了 btnpublishPlayerAudioClick")
            mediaPlayerKit.publishPlayerAudio()
        //}
        
    }
    
    @objc func btnInitRTCAction() {
        NSLog("打印了 初始化RTC")
        //初始化rtc
        initRTCinfo()
    }
    
    @objc func btnRoleBroadcastAction() {
        if agoraKit != nil {
            agoraKit.setClientRole(.broadcaster)
            intRole = 1
            NSLog("打印了 设置为broadcaster")
        }
    }
    
    @objc func btnRoleAudienceAction() {
        if agoraKit != nil {
            agoraKit.setClientRole(.audience)
            intRole = 2
            NSLog("打印了 设置为audience")
        }
    }
    
    @objc func btnGameStreamBeforeJoinAction() {
        if agoraKit != nil {
            agoraKit.setAudioProfile(.musicHighQualityStereo, scenario: .gameStreaming)
            NSLog("打印了 频道前RTC设为GameStream")
            lblshuoming3.text = "已切换为 GameStreaming"
        }
    }
    
    @objc func btnChatRoomBeforeJoinAction() {
        if agoraKit != nil {
            agoraKit.setAudioProfile(.default, scenario: .chatRoomGaming)
            NSLog("打印了 频道前RTC设为ChatRoom")
            lblshuoming3.text = "已切换为 chatRoomGaming"
            
        }
    }
    
    @objc func btnCreateInitMediaPlayAction() {
        NSLog("打印了 初始化MPK")
        if agoraKit != nil {
            mediaPlayerKit = AgoraRtcMediaPlayer.init(rtcEngine: agoraKit)
            mediaPlayerKit.setRtcMediaPlayerDelegate(self)
            mediaPlayerKit.setView(mpkLocalView)
        }
    }
    
    @objc func btnJoinChannelClick() {
        joinChannella()
    }
    
    @objc func btna2dp0Click() {
        agoraKit.setParameters("{\"che.audio.force.bluetooth.a2dp\":0}")
        
        NSLog("打印了 a2dp 为 0")
    }
    
    @objc func btna2dp1Click() {
        agoraKit.setParameters("{\"che.audio.force.bluetooth.a2dp\":1}")
        NSLog("打印了 a2dp 为 1")
    }
    
    @objc func btnDestroyRTCAction() {
        AgoraRtcEngineKit.destroy()
    }
        
    @objc func btnPalyAVPlayerAction() {
        
        self.audioPlayer.play()
        NSLog("打印了 AVAudioPlayer 播放")
        
        
        
        
//        let strurl = "http://music.163.com/song/media/outer/url?id=1808492017.mp3"
//        let url  = URL.init(fileURLWithPath: strurl)
//
//        //let strurl: String = Bundle.main.path(forResource: "jiandanai", ofType: "mp3")!
//        //let url  = URL.init(fileURLWithPath: strurl)
//
//        do {
//            let avauplay: AVAudioPlayer = try AVAudioPlayer.init(contentsOf: url)
//            avauplay.delegate = self;
//            avauplay.prepareToPlay()
//            avauplay.play()
//
//            NSLog("打印了  AVAudioPlayer 开始播放")
//
//        } catch  {
//            NSLog("打印了  AVAudioPlayer 播放错误")
//        }
    }
    
    func joinChannella() {
        
//        let config = AgoraRtcEngineConfig()
//        config.appId = ZSNComDef.AppId
//        config.areaCode = 0xFFFFFFFF
//        let logConfig = AgoraLogConfig()
//        logConfig.level = .info
//        config.logConfig = logConfig
//
//        agoraKit = AgoraRtcEngineKit.sharedEngine(with: config, delegate: self)
        
        let channelName = ZSNComDef.ChannelName
//        let resolution = CGSize(width: 1280, height: 720)
//        let fps = AgoraVideoFrameRate.fps60
//        let orientation = AgoraVideoOutputOrientationMode.fixedLandscape
//
//        //agoraKit.setAudioProfile(.musicHighQualityStereo, scenario: .gameStreaming)
//
//        //agoraKit.setParameters("{\"che.audio.keep.audiosession\": true}")
//
//        agoraKit.setAudioProfile(.musicHighQuality, scenario: .gameStreaming)
//        agoraKit.setChannelProfile(.liveBroadcasting)
//        agoraKit.setClientRole(.broadcaster)
//
//        agoraKit.enableAudio()
//        agoraKit.enableVideo()
//        agoraKit.setVideoEncoderConfiguration(AgoraVideoEncoderConfiguration(size: resolution,
//                frameRate: fps,
//                bitrate: AgoraVideoBitrateStandard,
//                orientationMode: orientation))
        
        let option = AgoraRtcChannelMediaOptions()
        let result = agoraKit.joinChannel(byToken: ZSNComDef.Token, channelId: channelName, info: nil, uid: 0, options: option)
        if result != 0 {
            NSLog("打印了 MPK进入频道失败 \(result)")
        }
        else {
            NSLog("打印了 MPK已进入频道2")
        }
    }
    
    func initRTCinfo() {
        let config = AgoraRtcEngineConfig()
        config.appId = ZSNComDef.AppId
        config.areaCode = 0xFFFFFFFF
        let logConfig = AgoraLogConfig()
        logConfig.level = .info
        config.logConfig = logConfig
        
        agoraKit = AgoraRtcEngineKit.sharedEngine(with: config, delegate: self)
//        agoraKit.setParameters("{\"rtc.log_filter\":65535}")

        let resolution = CGSize(width: 1280, height: 720)
        let fps = AgoraVideoFrameRate.fps15
        let orientation = AgoraVideoOutputOrientationMode.fixedLandscape
        //agoraKit.setAudioProfile(.default, scenario: .chatRoomGaming)
                
        //agoraKit.setAudioProfile(.musicHighQualityStereo, scenario: .gameStreaming)
        
        //agoraKit.setParameters("{\"che.audio.keep.audiosession\": true}")
        
        //agoraKit.setAudioProfile(.musicHighQuality, scenario: .gameStreaming)
        
        
        //agoraKit.setParameters("{\"che.audio.force.bluetooth.a2dp\":0}")
        
        //高音质配置begin
        //agoraKit.setAudioProfile(.musicHighQuality, scenario: .gameStreaming)
        //agoraKit.setParameters("{\"che.audio.specify.codec\": \"HEAAC_2ch\"}")
        //agoraKit.setParameters("{\"che.audio.codec.bitrate\": 80000}")
        
        //agoraKit.adjustRecordingSignalVolume(100)  //配置采集的音量
        //agoraKit.adjustPlaybackSignalVolume(100)   //此接口可调整；如果没有调整的，就设置100
        //高音质配置end
        
        agoraKit.setChannelProfile(.liveBroadcasting)
        if (intRole == 1) {
            agoraKit.setClientRole(.broadcaster)
        }
        else if (intRole == 2) {
            agoraKit.setClientRole(.audience)
        }
        else {
            agoraKit.setClientRole(.broadcaster)
        }
        
        agoraKit.enableAudio()
        agoraKit.enableVideo()
        agoraKit.setVideoEncoderConfiguration(AgoraVideoEncoderConfiguration(size: resolution,
                frameRate: fps,
                bitrate: AgoraVideoBitrateStandard,
                orientationMode: orientation))
    }
    
    
    @objc func btnLeaveChannelAction() {
        NSLog("打印了  btnLeaveChannelAction")
        
        agoraKit.leaveChannel { (stat) in
            NSLog("打印了 离开频道")
            
            // 如果要销毁 RTC,需要先销毁 MPK
        }
    }
    
//    @objc func btnCreatePlayYouChannelAction() {
//        //initmeplaya()
//        initmeplayb()
//    }
//
//    @objc func btnCreatePlayNoChannelAction() {
//        initmeplaya()
//    }
    
    @objc func btnSetClickAction() {
        //she
        if( useVoiceChat ){
//            do {
//                let session = AVAudioSession.sharedInstance()
//                //try session.setCategory(.record, mode: .default, options: [.defaultToSpeaker, .allowBluetooth])
//
//                try session.setCategory(.soloAmbient)
//                try session.setActive(true)
                useVoiceChat = false
                NSLog("打印了 SoloAmbient")
                agoraKit.setParameters("{\"che.audio.profileWithBuild-inAEC\":false}");
                agoraKit.setParameters("{\"che.audio.enable.playout.device\":false}")
                agoraKit.setParameters("{\"che.audio.enable.playout.device\":true}")

//            } catch let error as NSError {
//                print(error.localizedDescription)
//                return
//            }
        } else {
//            do {
//                let session = AVAudioSession.sharedInstance()
                //try session.setCategory(.record, mode: .default, options: [.defaultToSpeaker, .allowBluetooth])
                
//                try session.setCategory(.playAndRecord)
//                try session.setMode(.voiceChat)
//                try session.setActive(true)
                useVoiceChat = true
                NSLog(" VoiceChat")
                agoraKit.setParameters("{\"che.audio.profileWithBuild-inAEC\":true}");
                agoraKit.setParameters("{\"che.audio.enable.playout.device\":false}")
                agoraKit.setParameters("{\"che.audio.enable.playout.device\":true}")

//            } catch let error as NSError {
//                print(error.localizedDescription)
//                return
//            }
        }
    }
    
    @objc func btnGetClickAction() {
        //cha
        
        let session = AVAudioSession.init()
        let a = session.availableCategories
        let b = session.availableModes
        let c = session.categoryOptions
        
        let d = session.category
        let e = session.mode
        let f = session.currentRoute.outputs
        let ff = f.description
        
        //let g = session.se
        
        NSLog("打印了 category \(d)   mode \(e)  options\(c)  route \(f)")
        
        let  incc: Int = Int(c.rawValue)
        
//        if ((incc & 32) == 32) {
//            txtview.text = "Category: \(d.rawValue)" + "\n\n" + "Mode: \(e.rawValue)" + "\n\n" + "\(c.rawValue) a2dp"
//        }
//        else {
            txtview.text = "Category: \(d.rawValue)" + "\n\n" + "Mode: \(e.rawValue)"
        //}
        
        
        
        
        //c.
        
//        let aa = String(data:a, encoding: String.Encoding.utf8)
//
//        let dict:Dictionary = ["latitude":latitude,"longitude":longitude]
//        let data = try? JSONSerialization.data(withJSONObject: dict, options: [])


        
        
       // txtview.text =
    }
    
    @objc func btnDestroyPlayAction() {
        mediaPlayerKit.destroy()
        mediaPlayerKit = nil
        
        //agoraKit.setParameters("{\"che.audio.force.bluetooth.a2dp\":0}")
        
        NSLog("打印了 MPK为 nil")
        
        
        // 如果要销毁 RTC,需要先销毁 MPK
    }
    
//    //无关联频道创建MPK
//    func initmeplaya()  {
//        //agoraKit.setParameters("{\"che.audio.force.bluetooth.a2dp\":1}")
//        NSLog("打印了 创建 无 关联频道创建MPK")
//        mediaPlayerKit = AgoraRtcMediaPlayer.init(rtcEngine: agoraKit)
//        mediaPlayerKit.setRtcMediaPlayerDelegate(self)
//
//    }
//
//    //有关联频道创建MPK
//    func initmeplayb()  {
//        NSLog("打印了 创建 有 绑定RTC的MPK")
//        mediaPlayerKit = AgoraRtcMediaPlayer.init(rtcEngine: agoraKit)
//        mediaPlayerKit.setRtcMediaPlayerDelegate(self)
//    }
    
    
    @objc func btnOpenClickAction(sender: UIButton) {
        NSLog("打印了 MPK Open")
        
        //let url = "https://webdemo.agora.io/agora-web-showcase/examples/Agora-Custom-VideoSource-Web/assets/sample.mp4"
        
        //let url = "http://music.163.com/song/media/outer/url?id=1808492017.mp3"
        //let url =
        let url: String = Bundle.main.path(forResource: "shipina", ofType: "MP4")!
//        let url = "https://webdemo.agora.io/agora-web-showcase/examples/Agora-Custom-VideoSource-Web/assets/sample.mp4"
        
        if mediaPlayerKit != nil {
            mediaPlayerKit.open(url, startPos: 0)
            mediaPlayerKit.setLoopCount(-1)
        }
        else {
            NSLog("打印了 mediaPlayerKit为nil,Open请先创建mediaPlayerKit")
        }
        
        
    }
    
    @objc func btnPlayClickAction(sender: UIButton) {
        NSLog("打印了 MPK Play")
        if mediaPlayerKit != nil {
            mediaPlayerKit.play()
        }
        else {
            NSLog("打印了 mediaPlayerKit为nil,play请先创建mediaPlayerKit")
        }
        
        
    }
    
    @objc func btnStopClickAction(sender: UIButton) {
        NSLog("打印了 MPK stop")
        if mediaPlayerKit != nil {
            mediaPlayerKit.stop()
        }
        else {
            NSLog("打印了 mediaPlayerKit为nil,stop请先创建mediaPlayerKit")
        }
    }
    
    @objc func btnScenarioGameStreamingAction() {
        //3
        if agoraKit != nil {
            agoraKit.setParameters("{\"che.audio.switch.scenario\":3}")
            lblshuoming3.text = "已切换为 GameStreaming"
            
            NSLog("打印了 RTC设置 scenario 为3 AgoraAudioScenarioGameStreaming")
            
        }
        else {
            NSLog("打印了 agoraKit为nil,set 3请先创建agoraKit")
        }
    }
    
    @objc func btnScenarioChatRoomAction() {
        //5
        if agoraKit != nil {
            agoraKit.setParameters("{\"che.audio.switch.scenario\":5}")
            
            lblshuoming3.text = "已切换为 chatRoomGaming"
            
            NSLog("打印了 RTC设置 scenario 为5 AgoraAudioScenarioChatRoomGaming")
        }
        else {
            NSLog("打印了 agoraKit为nil,set 5请先创建agoraKit")
        }
    }
    
    
    func rtcEngine(_ engine: AgoraRtcEngineKit, didOccurWarning warningCode: AgoraWarningCode) {
        NSLog("打印了 didOccurWarning \(warningCode)")
    }
    
    func rtcEngine(_ engine: AgoraRtcEngineKit, didOccurError errorCode: AgoraErrorCode) {
        NSLog("打印了 didOccurError \(errorCode)")
    }
    
    
    func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinChannel channel: String, withUid uid: UInt, elapsed: Int) {
        NSLog("打印了 进入频道didJoinChannel \(channel) \(uid)  \(elapsed)")
        setupLocalVideo()
    }
    
    func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinedOfUid uid: UInt, elapsed: Int) {
        NSLog("打印了 didJoinedOfUid \(uid)  \(elapsed)")
        setupRemoteVideo(uid)
        
        //setupMPKRemoteVideo(uid)
    }
    
    func rtcEngine(_ engine: AgoraRtcEngineKit, didOfflineOfUid uid: UInt, reason: AgoraUserOfflineReason) {
        NSLog("打印了 didJoinedOfUid  uid:\(uid) reason: \(reason)")
    }

    
    //didAudioRouteChanged
    //
    
    func rtcEngine(_ engine: AgoraRtcEngineKit, didAudioRouteChanged routing: AgoraAudioOutputRouting) {
        
        NSLog("打印了 didAudioRouteChanged \(routing.rawValue)")
    }
    
    func agoraRtcMediaPlayer(_ playerKit: AgoraRtcMediaPlayer, didChangedToPosition position: Int) {
        //NSLog("打印了 media player didChangedToPosition \(position)")
        
    }
    
    func agoraRtcMediaPlayer(_ playerKit: AgoraRtcMediaPlayer, didPlayBufferUpdated playCachedBuffer: Int) {
        //NSLog("打印了 media player didPlayBufferUpdated ")
    }
    
    func agoraRtcMediaPlayer(_ playerKit: AgoraRtcMediaPlayer, didReceiveData data: String?, length: Int) {
        //NSLog("打印了 media player  didReceiveData")
    }
    
    func agoraRtcMediaPlayer(_ playerKit: AgoraRtcMediaPlayer, didPreloadEvent event: AgoraMediaPlayerPreloadEvent) {
        //NSLog("打印了 media player  didPreloadEvent")
    }
    
    func agoraRtcMediaPlayer(_ playerKit: AgoraRtcMediaPlayer, didChangedTo state: AgoraMediaPlayerState, error: AgoraMediaPlayerError) {
        //NSLog("打印了 状态media player  didChangedTo  \(state.rawValue)")
        
        if state == .stopped {
            //NSLog("打印了 状态media player  didChangedTo AgoraMediaPlayerStateStopped")
        }
        
        if state == .idle{
            //NSLog("打印了 状态media player  didChangedTo AgoraMediaPlayerStateIdle")
        }
    }
    
    func agoraRtcMediaPlayer(_ playerKit: AgoraRtcMediaPlayer, didOccur event: AgoraMediaPlayerEvent, elapsedTime time: Int, message: String?) {
        NSLog("打印了 media player didOccur ")
    }
    
    func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
        print("AudioPlayer error: ")
    }
    
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        print("AudioPlayer finished")
    }
    func audioPlayerBeginInterruption(_ player: AVAudioPlayer) {
        print("AudioPlayer begin interruption")
    }
    func audioPlayerEndInterruption(_ player: AVAudioPlayer, withOptions flags: Int) {
        print("AudioPlayer end interruption")
    }
    
}
